<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Api extends CI_Controller {

    public function __construct()
    {
        parent::__construct();
        $this->load->model(['server_model','siteorder_model','aliship_model','sitecategory_model','adword/adaccount_model','adword/adaccountreport_model','adword/adproducts_model']);
        $this->json=["status"=>0,"msg"=>"","data"=>[]];

        $this->tbid=[];
	}

    public function revive()
    {
		$token=$this->input->get("token");
		if(!$token)
		{
			die("error token");
		}
		else
		{
			$this->logfile=APPPATH.'logs'.DIRECTORY_SEPARATOR.$token.".txt";
			$this->getlog();
		}
       
        $items=$this->input->get("id");
        $cc=0;
        if($items)
        {
            foreach($items as $id)
            {
                if(empty($id)) continue;
              
                if(!in_array($id,$this->tbid))
                {
                    $cc++;
                    $this->tbid[]=$id;
                }
            }
        }
        if(count($this->tbid)>0)
        {
            $this->savelog();
        }
        $callback=$this->input->get("callbackparam");
        echo $callback.'('.json_encode([]).')';
        die();
	}
	

	public function clear()
    {
		$token=$this->input->get("token");
		if(!$token)
		{
			die("error token");
		}
		else
		{
			$this->logfile=APPPATH.'logs'.DIRECTORY_SEPARATOR.$token.".txt";
		}

		$this->tbid=[];
		
        if(file_exists($this->logfile))
        {
            unlink($this->logfile);
        }
        die("clear ok");
    }

    public function show()
    {
		$token=$this->input->get("token");
		if(!$token)
		{
			die("error token");
		}
		else
		{
			$this->logfile=APPPATH.'logs'.DIRECTORY_SEPARATOR.$token.".txt";
			$this->getlog();
		}

        foreach($this->tbid as $i)
        {
            echo "https://item.taobao.com/item.htm?id=".$i."<br/>";
        }
        die();
    }
    
    private function getlog()
    {
        if(file_exists($this->logfile))
        {
            $info=file_get_contents($this->logfile);
            $this->tbid=json_decode($info,true);
        }     
        
	}
	
	private function savelog()
    {
        $allinfo=json_encode($this->tbid);
        file_put_contents($this->logfile,$allinfo);
	}
    
    
    public function syncsitecat($siteid)
    {
        $info=$this->input->raw_input_stream;        
        $result=json_decode($info,true);
        $sitedata=$this->sitecategory_model->getcat($siteid);
        $mel=[];
        if($sitedata):
        foreach($sitedata as $val)
        {
            $mel[$val["rid"]]=$val;
        }
        endif;
        print_r($result);
        die();

        if(isset($result[2]["children"]) && $result[2]["children"])
        {
            foreach($result[2]["children"] as $k=>$v)
            {
                if(isset($mel[$v["id_category"]]) && $mel[$v["id_category"]])
                {

                }
                else
                {
                    $newdata=[
                        "name"=>$v["name"],
                        "pid"=>0,
                        "sort"=>$v["position"],
                        "siteid"=>$siteid,
                        "rid"=>$v["id_category"],
                        "addtime"=>$v["date_add"]
                    ];
                    $this->sitecategory_model->create($newdata);
                }
            }
        }
        die("ok");
    }
    
    public function fixrecord()
    {
        $shippment=$this->aliship_model->getfilter("status=0");
        foreach($shippment as $ship)
        {
            $track=json_decode($ship["tracklog"],true);
            if(isset($track["detailList"]) && count($track["detailList"])>0 && (strstr(strtolower($track["detailList"][0]["desc"]),"delivered")))
            {
                $newdata["status"]=1;
                $this->aliship_model->update($ship["id"],$newdata);
            }
        }

        echo "ok";
        die();
    }

    public function servediskinfo()
    {
        $info=$this->input->raw_input_stream;        
        $result=json_decode($info,true);
        if(isset($result["serverid"])&& isset($result["used"]) && isset($result["total"]))
        {
            $newdata=[
                "disktotal"=>$result["total"],
                "diskused"=>$result["used"],
                "lastupdate"=>date("Y-m-d H:i:s"),
            ];
            $this->server_model->update($result["serverid"],$newdata);
        }
        die("ok");
    }
    
    public function adswordproduct()
    {
        $info=$this->input->raw_input_stream;        
        $result=json_decode($info,true);
        if($result&&is_array($result)&&count($result)>0)
        {
            foreach($result as $item)
            {
                $acc=$this->adaccount_model->getfilter(["account"=>$item[12]]);
                if(!$acc) continue;
                $item[]=$acc[0]["id"];
                $this->adproducts_model->addinsert($item);
            }
        }
	    echo "ok";
        die();


    }


    public function adswordaccount()
    {

        $info=$this->input->raw_input_stream;
        $result=json_decode($info,true);
        if($result&&is_array($result)&&count($result)>0)
        {
            foreach($result as $item)
            {
                $acc=$this->adaccount_model->addinsert([$item[13],$item[1],$item[2]]);
                $item[]=$acc["id"];
                $this->adaccountreport_model->addinsert($item);
            }
        }

	    echo "ok";
        die();

    }


    public function recieve_ship()
    {
        $info=json_decode($this->input->raw_input_stream,true);
        $shippment=$this->aliship_model->getitembykey($info["ordersn"],"ordersn");
        if(!$shippment)
        {
            $newdata=[
                "ordersn"=>$info["ordersn"],
                "tracklog"=>json_encode($info["track"]),
                "status"=>0,
                "shiptype"=>$info["shiptype"],
                "shipnum"=>$info["shipnum"],
                "paytime"=>date("Y-m-d H:i:s",strtotime($info["paytime"])),
                "updatetime"=>date("Y-m-d H:i:s"),
                "disputetime"=>date("Y-m-d H:i:s",time()+intval($info["disputetime"]/1000))
            ];
            if(isset($info["track"]["detailList"]) && count($info["track"]["detailList"])>0 && (strstr(strtolower($info["track"]["detailList"][0]["desc"]),"delivered")))
            {
                $newdata["status"]=1;
            }
            if(isset($info["keydesc"]) && strstr(strtolower($info["keydesc"]),"delivered"))
            {
                $newdata["status"]=1;
            }
            $this->aliship_model->create($newdata);
            $this->json["status"]=1;
            $this->json["msg"]="new ship";
        }
        else if($shippment["status"]==0)
        {
            $newdata=[
                "tracklog"=>json_encode($info["track"]),
                "shipnum"=>$info["shipnum"],
                "updatetime"=>date("Y-m-d H:i:s"),
            ];
            if(isset($info["track"]["detailList"]) && count($info["track"]["detailList"])>0 && (strstr(strtolower($info["track"]["detailList"][0]["desc"]),"delivered")))
            {
                $newdata["status"]=1;
            }
            if(isset($info["keydesc"]) && strstr(strtolower($info["keydesc"]),"delivered"))
            {
                $newdata["status"]=1;
            }
            $this->aliship_model->update($shippment["id"],$newdata);
            $this->json["status"]=1;
            $this->json["msg"]="update ship";
        }
        else
        {
            $this->json["status"]=1;
            $this->json["msg"]="done ship";
        }
        $this->sendjson();
    }

    public function buyprice()
	{
		$info=json_decode($this->input->raw_input_stream,true);	
		$order=$this->siteorder_model->getbyalioid(trim($info["id"]));
		if($order)
		{
			if(empty($order["buyamount"]))
			{
				$newdata=["buyamount"=>$info["buyamount"]];
				$this->siteorder_model->update($order["id"], $newdata);
				$this->json["message"]="ok";
				$this->sendjson();
			}
			else
			{
				$this->json["message"]="采购价不为空";
				$this->sendjson();
			}
		}
		else
		{
			$this->json["message"]="没有找到订单";
			$this->sendjson();
		}

    }

    public function queryorder()
    {
        $info=json_decode($this->input->raw_input_stream,true);	
        $key = $info["key"];
        $type = $info["type"];
        $orders=$this->siteorder_model->queryorder($key,$type);
        $this->json["data"]=$orders;
        $this->sendjson();
    }

    public function queryorderlist()
    {
        $info=json_decode($this->input->raw_input_stream,true);	
        $pagesize = isset($info["pagesize"])?intval($info["pagesize"]):100;
        $page = isset($info["page"])?intval($info["page"]):1;
        $key = "";
        $siteid = "";
        $state = isset($info["state"])?trim($info["state"]):"";
        $timelimit=[];
        if(isset($info["start"]))
        {
            $timelimit["start"]=$info["start"];
        }
        if(isset($info["end"]))
        {
            $timelimit["end"]=$info["end"];
        }
        $page_data=$this->siteorder_model->getpage($siteid,$page,$pagesize,$key,0,$state,$timelimit);
        $this->json["data"]=$page_data["data"];
        $this->sendjson();
    }
    

    public function sforder()
    {
        $info=json_decode($this->input->raw_input_stream,true);	
        $order=$this->siteorder_model->getbyshipping(trim($info["miSFOrderNo"]));
        if($order)
        {
            $shippingfee = sprintf("%.2f",($info["tolAmt"]/7));
            $newdata=["shippingfee"=>$shippingfee];
			$this->siteorder_model->update($order["id"], $newdata);
            $this->json["message"]="ok";
      		$this->sendjson();
        }
        else
        {
            $this->json["message"]="没有找到订单";
			$this->sendjson();
        }
    }
    
    private function sendjson()
	{
		echo json_encode($this->json,JSON_UNESCAPED_UNICODE);
		die();
	}    
}
